package com.cindata

import com.cindata.dimension.CreditScoreRiskDimension
import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import com.cindata.dictionary.*

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.CREATED

@Secured(['isAuthenticated()'])
@Transactional
class ContactController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def developerApiService

    def contactList()
    {
    }

    def index()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def householdType = params["householdType"]
        def degree = params["degree"]
        def birthdayStart = params["birthdayStart"]
        def birthdayEnd = params["birthdayEnd"]
        def sex = params["sex"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def batch = params["batch"]

        def user = User.findById(springSecurityService.principal.id)

        def riskSql = "from ContactRiskWarningDisposition c where 1=1"
        def riskWarningStatus = params['riskWarningStatus']
        if (riskWarningStatus)
        {
            riskSql += " and c.status = '${riskWarningStatus}'"
        }
        def riskWarningDispositionType = params['riskWarningDispositionType']
        if (riskWarningDispositionType)
        {
            riskSql += " and c.type.id = ${riskWarningDispositionType}"
        }

        def dispositionSql = ""
        if (riskWarningStatus || riskWarningDispositionType)
        {
            def dispositionList = ContactRiskWarningDisposition.executeQuery(riskSql)*.contact.unique()
            if (dispositionList)
            {
                String dispositionIdList = dispositionList*.id?.toString()
                dispositionSql += " and e.id in (" + dispositionIdList?.substring(1, dispositionIdList.lastIndexOf("]")) + ")"
            }
            else
            {
                dispositionSql += " and e.id in ('-1')"
            }
        }

        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (dispositionSql)
        {
            sql += dispositionSql
        }
        if (address && address != "")
        {
            sql += " and e.address like :address"
            estateQueryParam['address'] = '%' + address + '%'
        }
        if (debitCardNumber && debitCardNumber != "")
        {
            sql += " and e.debitCardNumber like :debitCardNumber"
            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        }
        if (creditRiskLevel && creditRiskLevel != "")
        {
            def riskList = CreditScoreRiskDimension.list()
            riskList.each {
                if (it?.label == creditRiskLevel)
                {
                    def minScoreValue = it.minValue
                    def maxScoreValue = it.maxValue
                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
                }
            }
        }
        if (cellphone && cellphone != "")
        {
            sql += " and e.cellphone like :cellphone"
            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        }
        if (creditScoreStart && creditScoreStart != '')
        {
            sql += " and e.creditScore >= :creditScoreStart "
            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        }

        if (creditScoreEnd && creditScoreEnd != '')
        {
            sql += " and e.creditScore <= :creditScoreEnd "
            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        }
        if (fullName && fullName != "")
        {
            sql += " and e.fullName like :fullName"
            estateQueryParam['fullName'] = '%' + fullName + '%'
        }
        if (idNumber && idNumber != "")
        {
            sql += " and e.idNumber = :idNumber "
            estateQueryParam['idNumber'] = idNumber
        }
        if (birthdayStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(birthdayStart)
            sql += "and e.birthday >=  :dateStart "
            estateQueryParam['dateStart'] = dateStart
        }

        if (birthdayEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetDateBeginByDateStr(birthdayEnd)
            sql += "and e.birthday <=  :dateEnd "
            estateQueryParam['dateEnd'] = dateEnd
        }
        if (identityType && identityType != "")
        {
            sql += " and e.identityType.id = :identityType "
            estateQueryParam['identityType'] = Long.parseLong(identityType)
        }
        if (batch && batch != "")
        {
            sql += " and e.batch.id = :batch "
            estateQueryParam['batch'] = Long.parseLong(batch)
        }
        if (householdType && householdType != "")
        {
            sql += " and e.householdType = :householdType "
            estateQueryParam['householdType'] = householdType
        }
        if (degree && degree != "")
        {
            sql += " and e.degree = :degree "
            estateQueryParam['degree'] = degree
        }
        if (sex && sex != "")
        {
            sql += " and e.sex = :sex "
            estateQueryParam['sex'] = sex
        }

        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        contactSql += sql

        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond contactList, model: [contactList: contactList, contactCount: contactCount[0], params: params], view: 'index'
    }

    def show(Contact contact)
    {
        //贷款信息
        def mortgageList = MortgageContact.findAllByContact(contact)*.mortgage?.unique()
        respond contact, model: [mortgageList: mortgageList, contactDetail: contact], view: 'show'
    }

    def create()
    {
        respond new Contact(params)
    }

    @Transactional
    def save(Contact contact)
    {
        if (contact == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contact.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond contact.errors, view: 'create'
            return
        }

        contact.save flush: true

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        mortgageList.each {
            def mortgageContact = new MortgageContact()
            mortgageContact.mortgage = Mortgage.findById(it)
            mortgageContact.contact = contact
            mortgageContact.type = ContactType.findById(params['contactType'])
            if (mortgageContact.validate())
            {
                mortgageContact.save flush: true
            }
            else
            {
                println mortgageContact.errors
            }
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect contact
            }
            '*' { respond contact, [status: CREATED] }
        }
    }

    def edit(Contact contact)
    {
        respond contact
    }

    @Transactional
    def update(Contact contact)
    {
        if (contact == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contact.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond contact.errors, view: 'edit'
            return
        }

        contact.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect contact
            }
            '*' { respond contact, [status: OK] }
        }
    }

    @Transactional
    def delete(Contact contact)
    {

        if (contact == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        contact.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def createCommonContact()
    {
        params['targetUri'] = request.getHeader("referer")
        respond new Contact(params)
    }

    @Transactional
    def saveCommonContact(Contact contact)
    {
        if (contact == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        println contact.errors
        if (contact.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond contact.errors, view: 'createCommonContact'
            return
        }

        contact.save flush: true

        def collateral = params['collateral']
        def collateralContact = new CollateralContact()
        collateralContact.type = ContactType.findById(params['typeId'])
        collateralContact.contact = contact
        collateralContact.collateral = Collateral.findById(collateral)
        if (collateralContact.validate())
        {
            collateralContact.save flush: true
        }
        else
        {
            println collateralContact.errors
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect uri: params['targetUri']
            }
            '*' { respond contact, [status: CREATED] }
        }
    }

    def editCommonContact(Contact contact)
    {
        params['targetUri'] = request.getHeader("referer")
        respond contact
    }

    @Transactional
    def updateCommonContact(Contact contact)
    {
        if (contact == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        if (contact.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond contact.errors, view: 'editCommonContact'
            return
        }

        contact.save flush: true

        def collateral = params['collateral']
        def collateralContact = CollateralContact.findByCollateralAndContact(Collateral.findById(collateral), contact)
        collateralContact.type = ContactType.findById(params['typeId'])
        if (collateralContact.validate())
        {
            collateralContact.save flush: true
        }
        else
        {
            println collateralContact.errors
        }

        redirect uri: params['targetUri']
    }

    @Transactional
    def deleteCommonContact(Contact contact)
    {
        def collateralId = params['collateralId']
        def collateralContact = CollateralContact.findByCollateralAndContact(Collateral.findById(collateralId), contact)
        if (collateralContact)
        {
            collateralContact.delete flush: true
        }

        contact.delete flush: true

        redirect controller: 'estate', action: 'estateShow', id: collateralId
    }

    @Transactional
    def bigDataScoreQuery()
    {
        def status = "success"
        def type = params["type"]
        def ids = params["ids"]
        def creditRiskLevel = params["creditRiskLevel"]
        try
        {
            if (type == "initQuery")
            {
                println "=========初始化查询开始"
                def start = System.currentTimeMillis()
                def list = Contact.list()
                list.each {
                    it.creditScore = getRandom()
                    it?.creditLatestQueryDate = new Date()
                    if (it.validate())
                    {
                        it?.save()
                    }
                    else
                    {
                        println it?.errors
                    }
                }
                def end = System.currentTimeMillis()
                def time = (end - start) / 1000
                println "耗时：" + time + "秒。"
                println "=========初始化查询结束"
            }
            else if (type == "batchQuery")
            {
                println "=========批量查询开始"
                def idList = new ArrayList()
                if (ids)
                {
                    idList = ids.split(",")
                    println "===========idList=" + idList
                    idList?.each {
                        def contact = Contact.findById(Long.parseLong(it))
                        contact.creditScore = getRandom()
                        contact?.creditLatestQueryDate = new Date()
                        if (contact.validate())
                        {
                            contact?.save()
                        }
                        else
                        {
                            println contact?.errors
                        }
                    }
                }
                println "=========批量查询结束"
            }
            else if (type == "bigDataQuery")
            {
                println "=========大数据查询开始"
                def contactList = new ArrayList<Contact>()
                if (creditRiskLevel)
                {
                    def creditRiskList = creditRiskLevel.split(",")
                    println "============creditRiskList=" + creditRiskList
                    creditRiskList.each {
                        def riskList = CreditScoreRiskDimension.findByLabel(it)
                        def minValue = riskList.minValue
                        def maxValue = riskList.maxValue
                        contactList = Contact.executeQuery(" from Contact c where c.creditScore > ${minValue} and c.creditScore <= ${maxValue}")
                        println "===========contactList.size()=" + contactList.size() + it
                        contactList.each {
                            it.creditScore = getRandom()
                            it?.creditLatestQueryDate = new Date()
                            if (it.validate())
                            {
                                it?.save()
                            }
                            else
                            {
                                println it?.errors
                            }
                        }
                    }
                }
                println "=========大数据查询结束"
            }

        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status] as JSON)
    }

    def getRandomValue(Double val)
    {
        Double rvalue
        Random random = new Random()
        if (!val)
        {
            return random.nextInt(100)
        }
        int iv = random.nextInt(100)
        boolean isadd = random.nextBoolean()
        if (isadd)
        {
            rvalue = val + val / 10 * iv
        }
        else
        {
            rvalue = val - val / 10 * iv
        }
        return rvalue
    }

    @Transactional
    def initQuery()
    {
        def contactList = Contact.findAll()
        contactList?.each {
            it?.creditScore = getRandom()
            it?.creditLatestQueryDate = new Date()
            if (it.validate())
            {
                it?.save()
            }
            else
            {
                println it?.errors
            }
        }
        redirect action: 'index'
    }

    def getRandom()
    {
        Math.floor(Math.random() * 100)
    }

    //客户调查报告
    def customerSurveyReport()
    {
        def reportId = params['reportId']
        def contactSurveyReport = ContactSurveyReport.findById(reportId)
        println "customerSurveyReport   " + params
        if (contactSurveyReport)
        {
            def loansAmount = params['loansAmount'] ? params['loansAmount']?.toDouble() : 0
            def loansDuration = params['loansDuration'] ? params['loansDuration']?.toInteger() : 0
            def mortgageRatio = params['mortgageRatio']
            def mortgageRejectReason = params['mortgageRejectReason']
            def starRepaymentMode = params['starRepaymentMode']
            def loanMethod = params['loanMethod']
            def finalPayeeOfLoans = params['finalPayeeOfLoans']
            if (starRepaymentMode)
            {
                contactSurveyReport.starRepaymentMode = RepaymentModeDict.findById(starRepaymentMode)
            }
            if (loanMethod)
            {
                contactSurveyReport.loanMethod = LoanMethodDict.findById(loanMethod)
            }
            contactSurveyReport.loansAmount = loansAmount
            contactSurveyReport.loansDuration = loansDuration
            contactSurveyReport.mortgageRatio = mortgageRatio
            contactSurveyReport.mortgageRejectReason = mortgageRejectReason
            contactSurveyReport.finalPayeeOfLoans = finalPayeeOfLoans
            if (contactSurveyReport.validate())
            {
                contactSurveyReport.save flush: true
            }
            else
            {
                println contactSurveyReport.errors
            }
        }

        def a = ContactSurveyReport.list()
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def stage = params["stage"]
        def idNumber = params["idNumber"]
        def cellphone = params["cellphone"]
        def startDate = params["startDate"]
        def endDate = params["endDate"]

        def sql = "from ContactSurveyReport where 1=1"
        def queryParam = [:]
        if (fullName)
        {
            sql += " and contact.fullName like :fullName"
            queryParam['fullName'] = '%' + fullName + '%'
        }
        if (stage)
        {
            sql += " and stage = :stage"
            queryParam['stage'] = stage
        }
        if (idNumber)
        {
            sql += " and contact.idNumber = :idNumber"
            queryParam['idNumber'] = idNumber
        }
        if (cellphone)
        {
            sql += " and contact.cellphone = :cellphone"
            queryParam['cellphone'] = cellphone
        }
        if (startDate)
        {
            sql += " and createdDate > :startDate"
            queryParam['startDate'] = startDate
        }
        if (endDate)
        {
            sql += " and createdDate <= :endDate"
            queryParam['endDate'] = endDate
        }

        def list = ContactSurveyReport.executeQuery(sql, queryParam, [max: max, offset: offset])
        def count = ContactSurveyReport.executeQuery(sql, queryParam)

        respond list, model: [list: list, count: count, params: params]
    }

    //复查客户
    def reviewContactSurvey()
    {
        def id = params['id']
        def contactSurveyReport = ContactSurveyReport.findById(id)
        contactSurveyReport.stage = "已审核"
        contactSurveyReport.save flush: true

        render([status: "success"] as JSON)
    }

    //删除客户
    def deleteContactSurvey()
    {
        def id = params['id']
        def contactSurveyReport = ContactSurveyReport.findById(id)
        contactSurveyReport.delete flush: true

        render([status: "success"] as JSON)
    }

    //查看客户
    def customerShow(ContactSurveyReport contactSurveyReport)
    {
        respond contactSurveyReport
    }

    def createContactReport(Contact contact)
    {
        respond contact
    }

    def borrowerSave()
    {
        println "borrowerSave params:  " + params
        def fullName = params['fullName']
        def sex = params['sexA']
        def identityTypeCode = params['identityType']
        def birthday = params['birthday']
        def idNumber = params['idNumber']
        def accountNatureCode = params['accountNature']
        def cellphone = params['cellphone']
        def phone = params['phone']
        def monthlyIncome = params['monthlyIncome'] ? params['monthlyIncome']?.toDouble() : 0
        def zipCode = params['zipCode']
        def address = params['address']
        def workUnitName = params['workUnitName']
        def workUnitAddress = params['workUnitAddress']
        def maritalStatus = params['maritalStatus']
        def spouseFullName = params['spouseFullName']
        def spouseCellphone = params['spouseCellphone']
        def spouseIdentityTypeCode = params['spouseIdentityType']
        def spouseIdNumber = params['spouseIdNumber']
        def user = User.findById(springSecurityService.principal.id)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        def contactSurvey = new ContactSurvey()
        def contactSurveyReport = new ContactSurveyReport()

        contactSurveyReport.account = user.account
        contactSurvey.fullName = fullName
        contactSurvey.sex = sex
        contactSurvey.idNumber = idNumber
        contactSurvey.cellphone = cellphone
        contactSurvey.phone = phone
        contactSurvey.monthlyIncome = monthlyIncome
        contactSurvey.zipCode = zipCode
        contactSurvey.address = address
        contactSurvey.workUnitName = workUnitName
        contactSurvey.workUnitAddress = workUnitAddress
        contactSurvey.maritalStatus = maritalStatus
        contactSurvey.spouseFullName = spouseFullName
        contactSurvey.spouseCellphone = spouseCellphone
        contactSurvey.spouseIdNumber = spouseIdNumber

        if (identityTypeCode)
        {
            contactSurvey.identityType = ContactIdentityType.findById(identityTypeCode)
        }
        if (spouseIdentityTypeCode)
        {
            contactSurvey.spouseIdentityType = ContactIdentityType.findById(spouseIdentityTypeCode)
        }
        if (birthday)
        {
            contactSurvey.birthday = sdf.parse(birthday)
        }
        if (accountNatureCode)
        {
            contactSurvey.accountNature = AccountNatureDict.findByCode(accountNatureCode)
        }
        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
            contactSurvey.report = contactSurveyReport
        }
        else
        {
            println contactSurveyReport.errors
        }

        if (contactSurvey.validate())
        {
            contactSurvey.save flush: true
            contactSurveyReport.contact = contactSurvey
            contactSurveyReport.save flush: true
        }
        else
        {
            println contactSurvey.errors
        }
        println "id:  " + contactSurvey.id
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'contactSurveyReport.label', default: 'ContactSurveyReport'), contactSurveyReport.id])
                redirect action: 'createClient', params: [reportId: contactSurveyReport.id, contactId: contactSurvey.id]
            }
            '*' { respond contactSurveyReport, [status: CREATED] }
        }
    }

    def borrowerSave2()
    {
        println "borrowerSave2 params: " + params
        def reportId = params['reportId']
        def contactId = params['contactId']
        def fullName = params['fullName']
        def sex = params['sexA']
        def identityTypeCode = params['identityType']
        def birthday = params['birthday']
        def idNumber = params['idNumber']
        def accountNatureCode = params['accountNature']
        def cellphone = params['cellphone']
        def phone = params['phone']
        def monthlyIncome = params['monthlyIncome'] ? params['monthlyIncome']?.toDouble() : 0
        def zipCode = params['zipCode']
        def address = params['address']
        def workUnitName = params['workUnitName']
        def workUnitAddress = params['workUnitAddress']
        def maritalStatus = params['maritalStatus']
        def spouseFullName = params['spouseFullName']
        def spouseCellphone = params['spouseCellphone']
        def spouseIdentityTypeCode = params['spouseIdentityType']
        def spouseIdNumber = params['spouseIdNumber']
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        def contactSurvey = new ContactSurvey()
        def contactSurveyReport = ContactSurveyReport.findById(reportId)
        contactSurvey.report = contactSurveyReport

        contactSurvey.fullName = fullName
        contactSurvey.sex = sex
        contactSurvey.idNumber = idNumber
        contactSurvey.cellphone = cellphone
        contactSurvey.phone = phone
        contactSurvey.monthlyIncome = monthlyIncome
        contactSurvey.zipCode = zipCode
        contactSurvey.address = address
        contactSurvey.workUnitName = workUnitName
        contactSurvey.workUnitAddress = workUnitAddress
        contactSurvey.maritalStatus = maritalStatus
        contactSurvey.spouseFullName = spouseFullName
        contactSurvey.spouseCellphone = spouseCellphone
        contactSurvey.spouseIdNumber = spouseIdNumber

        if (identityTypeCode)
        {
            contactSurvey.identityType = ContactIdentityType.findById(identityTypeCode)
        }
        if (spouseIdentityTypeCode)
        {
            contactSurvey.spouseIdentityType = ContactIdentityType.findById(spouseIdentityTypeCode)
        }
        if (birthday)
        {
            contactSurvey.birthday = sdf.parse(birthday)
        }
        if (accountNatureCode)
        {
            contactSurvey.accountNature = AccountNatureDict.findByCode(accountNatureCode)
        }
        if (contactSurvey.validate())
        {
            contactSurvey.save flush: true
        }
        else
        {
            println contactSurvey.errors
        }
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'contactSurveyReport.label', default: 'ContactSurveyReport'), contactSurveyReport.id])
                redirect action: 'createClient', params: [contactId2: contactSurvey.id, contactId: contactId, reportId: contactSurveyReport?.id, isSecond: isSecond]
            }
            '*' { respond contactSurveyReport, [status: CREATED] }
        }
    }

    //新增客户
    def createClient()
    {
        println "createClient  parms: " + params
        def contactSurveyReport
        def contactSurvey
        def contactSurvey2
        def reportId = params['reportId']
        def contactId = params['contactId']
        def contactId2 = params['contactId2']
        if (contactId)
        {
            contactSurvey = ContactSurvey.findById(contactId)
        }
        if (contactId2)
        {
            contactSurvey2 = ContactSurvey.findById(contactId2)
        }
        if (reportId)
        {
            contactSurveyReport = ContactSurveyReport.findById(reportId)
        }
        println "createClient contactSurveyReport:  " + contactSurveyReport
        respond params, model: [contactSurveyReport: contactSurveyReport, contactSurvey: contactSurvey, contactSurvey2: contactSurvey2]

    }

    //新增客户资信状况
    def createClientCreditStatus()
    {
        println "createClientCreditStatus:  " + params
        def reportId = params['reportId']
        def contactId = params['contactId']
        def contactId2 = params['contactId2']
        def contactSurveyReport = ContactSurveyReport.findById(reportId)
        def contactSurvey = ContactSurvey.findById(contactId)
        def contactSurvey2 = ContactSurvey.findById(contactId2)
        println "contactSurveyReport:  " + contactSurveyReport
        println "contactSurvey:  " + contactSurvey
        println "contactSurvey2:  " + contactSurvey2
        def loansAmount = params['loansAmount'] ? params['loansAmount']?.toDouble() : 0
        def loansDuration = params['loansDuration'] ? params['loansDuration']?.toInteger() : 0
        def acceptableLoansAmount = params['acceptableLoansAmount'] ? params['acceptableLoansAmount']?.toDouble() : 0
        def applicationDate = params['applicationDate']
        def isCombinationLoans = params['isCombinationLoans']
        def depositBaseOnCurrent = params['depositBaseOnCurrent'] ? params['depositBaseOnCurrent']?.toDouble() : 0
        def depositAmountOnCurrent = params['depositAmountOnCurrent'] ? params['depositAmountOnCurrent']?.toDouble() : 0
        def starRepaymentMode = params['starRepaymentMode']
        def loanMethod = params['loanMethod']
        def guaranteeInstitution = params['guaranteeInstitution']
        def loanRecipient = params['loanRecipient']
        def advanceLoanStage = params['advanceLoanStage']
        def housingLoansAccount = params['housingLoansAccount']
        def loansBank = params['loansBank']

        contactSurveyReport.loansAmount = loansAmount
        contactSurveyReport.loansDuration = loansDuration
        contactSurveyReport.acceptableLoansAmount = acceptableLoansAmount
        if (applicationDate)
        {
            contactSurveyReport.applicationDate = Date.parse("yyyy-MM-dd", applicationDate)
        }
        contactSurveyReport.isCombinationLoans = isCombinationLoans
        contactSurveyReport.depositBaseOnCurrent = depositBaseOnCurrent
        contactSurveyReport.depositAmountOnCurrent = depositAmountOnCurrent
        contactSurveyReport.guaranteeInstitution = guaranteeInstitution
        contactSurveyReport.loanRecipient = loanRecipient
        contactSurveyReport.advanceLoanStage = advanceLoanStage
        contactSurveyReport.housingLoansAccount = housingLoansAccount
        contactSurveyReport.loansBank = loansBank
        if (starRepaymentMode)
        {
            contactSurveyReport.starRepaymentMode = RepaymentModeDict.findByCode(starRepaymentMode)
        }
        if (loanMethod)
        {
            contactSurveyReport.starRepaymentMode = RepaymentModeDict.findByCode(loanMethod)
        }
        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
        }
        else
        {
            println contactSurveyReport.errors
        }
        respond contactSurveyReport, model: [contactSurveyReport: contactSurveyReport, contactSurvey2: contactSurvey2, contactSurvey: contactSurvey]
    }

    def financialLoanSave()
    {
        println "financialLoanSave params:  " + params
        def contactId = params['contactId1']
        def contactId2 = params['contactId2']
        def contactSurvey
        def contactSurvey2
        def creditOverdueRecord = params['creditOverdueRecord1']
        def creditDefaultingRecord = params['creditDefaultingRecord1']
        def creditSearchingTimesInHalfYear = params['creditSearchingTimesInHalfYear1']
        def spouseCreditOverdueRecord = params['spouseCreditOverdueRecord1']
        def spouseCreditDefaultingRecord = params['spouseCreditDefaultingRecord1']
        def spouseCreditSearchingTimesInHalfYear = params['spouseCreditSearchingTimesInHalfYear1']

        def creditOverdueRecord2 = params['creditOverdueRecord2']
        def creditDefaultingRecord2 = params['creditDefaultingRecord2']
        def creditSearchingTimesInHalfYear2 = params['creditSearchingTimesInHalfYear2']
        def spouseCreditOverdueRecord2 = params['spouseCreditOverdueRecord2']
        def spouseCreditDefaultingRecord2 = params['spouseCreditDefaultingRecord2']
        def spouseCreditSearchingTimesInHalfYear2 = params['spouseCreditSearchingTimesInHalfYear2']

        contactSurvey = ContactSurvey.findById(contactId)
        contactSurvey.creditOverdueRecord = creditOverdueRecord
        contactSurvey.creditDefaultingRecord = creditDefaultingRecord
        contactSurvey.creditSearchingTimesInHalfYear = creditSearchingTimesInHalfYear
        contactSurvey.spouseCreditOverdueRecord = spouseCreditOverdueRecord
        contactSurvey.spouseCreditDefaultingRecord = spouseCreditDefaultingRecord
        contactSurvey.spouseCreditSearchingTimesInHalfYear = spouseCreditSearchingTimesInHalfYear
        def status
        if (contactSurvey.validate())
        {
            contactSurvey.save flush: true
            status = "success"
        }
        else
        {
            status = "fail"
            println contactSurvey.errors
        }
        if (contactId2)
        {
            contactSurvey2 = ContactSurvey.findById(contactId2)
            contactSurvey2.creditOverdueRecord = creditOverdueRecord2
            contactSurvey2.creditDefaultingRecord = creditDefaultingRecord2
            contactSurvey2.creditSearchingTimesInHalfYear = creditSearchingTimesInHalfYear2
            contactSurvey2.spouseCreditOverdueRecord = spouseCreditOverdueRecord2
            contactSurvey2.spouseCreditDefaultingRecord = spouseCreditDefaultingRecord2
            contactSurvey2.spouseCreditSearchingTimesInHalfYear = spouseCreditSearchingTimesInHalfYear2
            if (contactSurvey2.validate())
            {
                contactSurvey2.save flush: true
                status = "success"
            }
            else
            {
                status = "fail"
                println contactSurvey2.errors
            }
        }
        render([status: status] as JSON)
    }

    def originalDebtSave()
    {
        println "originalDebtSave params:  " + params
        def contactId = params['contactId1']
        def contactId2 = params['contactId2']
        def contactSurvey
        def contactSurvey2
        def debtType = params['debtType1']
        def debtMount = params['debtMount1'] ? params['debtMount1']?.toInteger() : 0
        def loansBalance = params['loansBalance1'] ? params['loansBalance1']?.toDouble() : 0
        def repaymentMountPerMon = params['repaymentMountPerMon1'] ? params['repaymentMountPerMon1']?.toDouble() : 0
        def memo = params['memo1']
        def overdraftAmount = params['overdraftAmount1'] ? params['overdraftAmount1']?.toDouble() : 0
        def guaranteeForOthersAmount = params['guaranteeForOthersAmount1'] ? params['guaranteeForOthersAmount1']?.toDouble() : 0

        def debtType2 = params['debtType2']
        def debtMount2 = params['debtMount2'] ? params['debtMount2']?.toInteger() : 0
        def loansBalance2 = params['loansBalance2'] ? params['loansBalance2']?.toDouble() : 0
        def repaymentMountPerMon2 = params['repaymentMountPerMon2'] ? params['repaymentMountPerMon2']?.toDouble() : 0
        def memo2 = params['memo2']
        def overdraftAmount2 = params['overdraftAmount2'] ? params['overdraftAmount2']?.toDouble() : 0
        def guaranteeForOthersAmount2 = params['guaranteeForOthersAmount2'] ? params['guaranteeForOthersAmount2']?.toDouble() : 0

        contactSurvey = ContactSurvey.findById(contactId)
        contactSurvey.debtType = debtType
        contactSurvey.debtMount = debtMount
        contactSurvey.loansBalance = loansBalance
        contactSurvey.repaymentMountPerMon = repaymentMountPerMon
        contactSurvey.memo = memo
        contactSurvey.overdraftAmount = overdraftAmount
        contactSurvey.guaranteeForOthersAmount = guaranteeForOthersAmount
        def status
        if (contactSurvey.validate())
        {
            contactSurvey.save flush: true
            status = "success"
        }
        else
        {
            status = "fail"
            println contactSurvey.errors
        }
        if (contactId2)
        {
            contactSurvey2 = ContactSurvey.findById(contactId2)
            contactSurvey2.debtType = debtType2
            contactSurvey2.debtMount = debtMount2
            contactSurvey2.loansBalance = loansBalance2
            contactSurvey2.repaymentMountPerMon = repaymentMountPerMon2
            contactSurvey2.memo = memo2
            contactSurvey2.overdraftAmount = overdraftAmount2
            contactSurvey2.guaranteeForOthersAmount = guaranteeForOthersAmount2
            if (contactSurvey2.validate())
            {
                contactSurvey2.save flush: true
                status = "success"
            }
            else
            {
                status = "fail"
                println contactSurvey2.errors
            }
        }
        render([status: status] as JSON)
    }

    //新增客户所购房产情况
    def createClientCollateralPurchase()
    {
        println "createClientCollateralPurchase params:  " + params
        def reportId = params['reportId']
        def contactId = params['contactId1']
        def contactId2 = params['contactId2']
        def contactSurveyReport = ContactSurveyReport.findById(reportId)
        def contactSurvey = ContactSurvey.findById(contactId)
        def contactSurvey2 = ContactSurvey.findById(contactId2)
        println "contactSurveyReport:  " + contactSurveyReport
        println "contactSurvey:  " + contactSurvey
        println "contactSurvey2:  " + contactSurvey2
        def workUnitName = params['workUnitName1']
        def workUnitAddress = params['workUnitAddress1']
        def workUnitNature = params['workUnitNature1']
        def workUnitPhone = params['workUnitPhone1']
        def numberCheckChannel = params['numberCheckChannel1']
        def workUnitCheckDate = params['workUnitCheckDate1']
        def checkContent = params['checkContent1']
        def checkReceiver = params['checkReceiver1']
        def checkReceiverIdentity = params['checkReceiverIdentity1']
        def answeredSituation = params['answeredSituation1']
        def abnormalMeno = params['abnormalMeno1']
        def actuallyCheckSituation = params['actuallyCheckSituation1']

        def fundDepositStartDate = params['fundDepositStartDate1']
        def fundDepositEndDate = params['fundDepositEndDate1']
        def fundDepositDuration = params['fundDepositDuration1'] ? params['fundDepositDuration1']?.toInteger() : 0
        def fundDepositAmountPerMon = params['fundDepositAmountPerMon1'] ? params['fundDepositAmountPerMon1']?.toDouble() : 0
        def fundDepositRatio = params['fundDepositRatio1'] ? params['fundDepositRatio1']?.toDouble() : 0
        def fundDepositBaseAmount = params['fundDepositBaseAmount1'] ? params['fundDepositBaseAmount1']?.toDouble() : 0
        def fundOpenedBank = params['fundOpenedBank1']
        def fundBalance = params['fundBalance1'] ? params['fundBalance1']?.toDouble() : 0
        def fundAccount = params['fundAccount1']
        def monthlyTotalIncome = params['monthlyTotalIncome1'] ? params['monthlyTotalIncome1']?.toDouble() : 0
        contactSurvey.workUnitName = workUnitName
        contactSurvey.workUnitAddress = workUnitAddress
        contactSurvey.workUnitPhone = workUnitPhone
        contactSurvey.numberCheckChannel = numberCheckChannel
        contactSurvey.numberCheckChannel = numberCheckChannel

        contactSurvey.checkContent = checkContent
        contactSurvey.checkReceiver = checkReceiver
        contactSurvey.checkReceiverIdentity = checkReceiverIdentity
        contactSurvey.answeredSituation = answeredSituation
        contactSurvey.abnormalMeno = abnormalMeno
        contactSurvey.actuallyCheckSituation = actuallyCheckSituation

        contactSurvey.fundDepositDuration = fundDepositDuration
        contactSurvey.fundDepositAmountPerMon = fundDepositAmountPerMon
        contactSurvey.fundDepositRatio = fundDepositRatio
        contactSurvey.fundDepositBaseAmount = fundDepositBaseAmount
        contactSurvey.fundOpenedBank = fundOpenedBank
        contactSurvey.fundBalance = fundBalance
        contactSurvey.fundAccount = fundAccount
        contactSurvey.monthlyTotalIncome = monthlyTotalIncome
        if (workUnitNature)
        {
            contactSurvey.workUnitNature = OrganizationNatureDict.findById(workUnitNature)
        }
        if (workUnitCheckDate)
        {
            contactSurvey.workUnitCheckDate = Date.parse("yyyy-MM-dd HH:mm:ss", workUnitCheckDate)
        }
        if (fundDepositStartDate)
        {
            contactSurvey.fundDepositStartDate = Date.parse("yyyy-MM-dd HH:mm:ss", fundDepositStartDate)
        }
        if (fundDepositEndDate)
        {
            contactSurvey.fundDepositEndDate = Date.parse("yyyy-MM-dd HH:mm:ss", fundDepositEndDate)
        }
        def coOwnersMonTotalIncome = params['coOwnersMonTotalIncome'] ? params['coOwnersMonTotalIncome']?.toDouble() : 0

        contactSurveyReport.coOwnersMonTotalIncome = coOwnersMonTotalIncome
        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
        }
        else
        {
            println contactSurveyReport.errors
        }

        if (contactSurvey.validate())
        {
            contactSurvey.save flush: true
        }
        else
        {
            println contactSurvey.errors
        }

        if (contactSurvey2)
        {
            def workUnitName2 = params['workUnitName2']
            def workUnitAddress2 = params['workUnitAddress2']
            def workUnitNature2 = params['workUnitNature2']
            def workUnitPhone2 = params['workUnitPhone2']
            def numberCheckChannel2 = params['numberCheckChannel2']
            def workUnitCheckDate2 = params['workUnitCheckDate2']
            def checkContent2 = params['checkContent2']
            def checkReceiver2 = params['checkReceiver2']
            def checkReceiverIdentity2 = params['checkReceiverIdentity2']
            def answeredSituation2 = params['answeredSituation2']
            def abnormalMeno2 = params['abnormalMeno2']
            def actuallyCheckSituation2 = params['actuallyCheckSituation2']

            def fundDepositStartDate2 = params['fundDepositStartDate2']
            def fundDepositEndDate2 = params['fundDepositEndDate2']
            def fundDepositDuration2 = params['fundDepositDuration2'] ? params['fundDepositDuration2']?.toInteger() : 0
            def fundDepositAmountPerMon2 = params['fundDepositAmountPerMon2'] ? params['fundDepositAmountPerMon2']?.toDouble() : 0
            def fundDepositRatio2 = params['fundDepositRatio2'] ? params['fundDepositRatio2']?.toDouble() : 0
            def fundDepositBaseAmount2 = params['fundDepositBaseAmount2'] ? params['fundDepositBaseAmount2']?.toDouble() : 0
            def fundOpenedBank2 = params['fundOpenedBank2']
            def fundBalance2 = params['fundBalance2'] ? params['fundBalance2']?.toDouble() : 0
            def fundAccount2 = params['fundAccount2']
            def monthlyTotalIncome2 = params['monthlyTotalIncome2'] ? params['monthlyTotalIncome2']?.toDouble() : 0
            contactSurvey2.workUnitName = workUnitName2
            contactSurvey2.workUnitAddress = workUnitAddress2
            contactSurvey2.workUnitPhone = workUnitPhone2
            contactSurvey2.numberCheckChannel = numberCheckChannel2
            contactSurvey2.numberCheckChannel = numberCheckChannel2
            contactSurvey2.checkContent = checkContent2
            contactSurvey2.checkReceiver = checkReceiver2
            contactSurvey2.checkReceiverIdentity = checkReceiverIdentity2
            contactSurvey2.answeredSituation = answeredSituation2
            contactSurvey2.abnormalMeno = abnormalMeno2
            contactSurvey2.actuallyCheckSituation = actuallyCheckSituation2

            contactSurvey2.fundDepositDuration = fundDepositDuration2
            contactSurvey2.fundDepositAmountPerMon = fundDepositAmountPerMon2
            contactSurvey2.fundDepositRatio = fundDepositRatio2
            contactSurvey2.fundDepositBaseAmount = fundDepositBaseAmount2
            contactSurvey2.fundOpenedBank = fundOpenedBank2
            contactSurvey2.fundBalance = fundBalance2
            contactSurvey2.fundAccount = fundAccount2
            contactSurvey2.monthlyTotalIncome = monthlyTotalIncome2
            if (workUnitNature2)
            {
                contactSurvey2.workUnitNature = OrganizationNatureDict.findById(workUnitNature2)
            }
            if (workUnitCheckDate2)
            {
                contactSurvey2.workUnitCheckDate = Date.parse("yyyy-MM-dd HH:mm:ss", workUnitCheckDate2)
            }
            if (fundDepositStartDate2)
            {
                contactSurvey2.fundDepositStartDate = Date.parse("yyyy-MM-dd HH:mm:ss", fundDepositStartDate2)
            }
            if (fundDepositEndDate2)
            {
                contactSurvey2.fundDepositEndDate = Date.parse("yyyy-MM-dd HH:mm:ss", fundDepositEndDate2)
            }
            if (contactSurvey2.validate())
            {
                contactSurvey2.save flush: true
            }
            else
            {
                println contactSurvey2.errors
            }
        }

        def editType = params['editType']
        if (editType)
        {
            def contactSurveyList = contactSurveyReport.contacts
            println "contactSurveyList:  " + contactSurveyList
            redirect action: 'editClientCollateralPurchase', method: "GET", params: [id: contactSurveyReport?.id]
        }
        else
        {
            respond contactSurveyReport, model: [contactSurveyReport: contactSurveyReport, contactSurvey2: contactSurvey2, contactSurvey: contactSurvey]
        }

    }

    //新增客户贷款风险评估
    def createClientLoanRiskEvaluation()
    {
        println "createClientLoanRiskEvaluation:  " + params
        def reportId = params['reportId']
        def contactSurveyReport = ContactSurveyReport.findById(reportId)
        println "contactSurveyReport:  " + contactSurveyReport
        def sourceAddress = params['sourceAddress']
        def sourceBuildArea = params['sourceBuildArea'] ? params['sourceBuildArea']?.toDouble() : 0
        def houseOwner = params['houseOwner']

        def houseAge = params['houseAge'] ? params['houseAge']?.toInteger() : 0
        def transactionPrice = params['transactionPrice'] ? params['transactionPrice']?.toDouble() : 0
        def firstPayment = params['firstPayment'] ? params['firstPayment']?.toDouble() : 0
        def firstPaymentRatio = params['firstPaymentRatio'] ? params['firstPaymentRatio']?.toDouble() : 0
        def orientation = params['orientation']
        def evaluateTotalPrice = params['evaluateTotalPrice'] ? params['evaluateTotalPrice']?.toDouble() : 0
        //        def evaluateUnitPrice=params['evaluateUnitPrice']? params['evaluateUnitPrice']?.toDouble() : 0
        def isPriceReasonable = params['isPriceReasonable']

        def houseNature = params['houseNature']
        def houseType = params['houseType']
        def finalPayeeOfLoans = params['finalPayeeOfLoans']
        def ohterPayeeOfLoans = params['ohterPayeeOfLoans']
        def evaluateDate = params['evaluateDate']
        def evaluateAccount = params['evaluateAccount']
        def evaluateReportNumber = params['evaluateReportNumber']
        def houseRealSituationRecord = params['houseRealSituationRecord']
        if (evaluateDate)
        {
            contactSurveyReport.evaluateDate = Date.parse("yyyy-MM-dd", evaluateDate)
        }
        contactSurveyReport.sourceAddress = sourceAddress
        contactSurveyReport.sourceBuildArea = sourceBuildArea
        contactSurveyReport.houseOwner = houseOwner
        contactSurveyReport.houseAge = houseAge
        contactSurveyReport.transactionPrice = transactionPrice
        contactSurveyReport.firstPayment = firstPayment
        contactSurveyReport.firstPaymentRatio = firstPaymentRatio
        contactSurveyReport.orientation = orientation
        contactSurveyReport.evaluateTotalPrice = evaluateTotalPrice
        contactSurveyReport.isPriceReasonable = isPriceReasonable
        contactSurveyReport.houseNature = houseNature

        contactSurveyReport.houseType = houseType
        contactSurveyReport.finalPayeeOfLoans = finalPayeeOfLoans
        contactSurveyReport.ohterPayeeOfLoans = ohterPayeeOfLoans
        contactSurveyReport.evaluateAccount = evaluateAccount
        contactSurveyReport.evaluateReportNumber = evaluateReportNumber
        contactSurveyReport.houseRealSituationRecord = houseRealSituationRecord
        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
        }
        else
        {
            println contactSurveyReport.errors
        }
        respond contactSurveyReport, model: [contactSurveyReport: contactSurveyReport]
    }

    //新增客户贷款调查意见
    def createClientLoanOpinion()
    {
        println "createClientLoanOpinion:  " + params
        def reportId = params['reportId']
        def contactSurveyReport = ContactSurveyReport.findById(reportId)
        println "contactSurveyReport:  " + contactSurveyReport


        def loanNumber = params['loanNumber'] ? params['loanNumber']?.toInteger() : 0
        def loansDuration = params['loansDuration'] ? params['loansDuration']?.toInteger() : 0
        def loansAmount = params['loansAmount'] ? params['loansAmount']?.toDouble() : 0
        def commonExpendPrice = params['commonExpendPrice'] ? params['commonExpendPrice']?.toDouble() : 0
        def commonTotalRepaymentPrice = params['commonTotalRepaymentPrice'] ? params['commonTotalRepaymentPrice']?.toDouble() : 0
        def expenditureIncomeRatio = params['expenditureIncomeRatio'] ? params['expenditureIncomeRatio']?.toDouble() : 0
        def mortgageRate = params['mortgageRate'] ? params['mortgageRate']?.toDouble() : 0
        def mortgageWarningMemo = params['mortgageWarningMemo']

        contactSurveyReport.loanNumber = loanNumber
        contactSurveyReport.loansDuration = loansDuration
        contactSurveyReport.loansAmount = loansAmount
        contactSurveyReport.commonExpendPrice = commonExpendPrice
        contactSurveyReport.commonTotalRepaymentPrice = commonTotalRepaymentPrice
        contactSurveyReport.expenditureIncomeRatio = expenditureIncomeRatio
        contactSurveyReport.mortgageRate = mortgageRate
        contactSurveyReport.mortgageWarningMemo = mortgageWarningMemo

        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
        }
        else
        {
            println contactSurveyReport.errors
        }
        respond contactSurveyReport, model: [contactSurveyReport: contactSurveyReport]
    }

    //修改客户信息
    def editClient(ContactSurveyReport contactSurveyReport)
    {
        def contactSurveyList = contactSurveyReport.contacts
        respond contactSurveyReport, model: [contactSurveyList: contactSurveyList, contactSurveyReport: contactSurveyReport]
    }

    def editContactSurvey()
    {
        println "editContactSurvey params:  " + params
        def id = params['id']
        def fullName = params['fullName']
        def sex = params['sex']
        def identityTypeCode = params['identityType']
        def birthday = params['birthday']
        def idNumber = params['idNumber']
        def accountNatureCode = params['accountNature']
        def cellphone = params['cellphone']
        def phone = params['phone']
        def monthlyIncome = params['monthlyIncome'] ? params['monthlyIncome']?.toDouble() : 0
        def zipCode = params['zipCode']
        def address = params['address']
        def workUnitName = params['workUnitName']
        def workUnitAddress = params['workUnitAddress']
        def maritalStatus = params['maritalStatus']
        def spouseFullName = params['spouseFullName']
        def spouseCellphone = params['spouseCellphone']
        def spouseIdentityTypeCode = params['spouseIdentityType']
        def spouseIdNumber = params['spouseIdNumber']
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        def contactSurvey = ContactSurvey.findById(id)

        contactSurvey.fullName = fullName
        contactSurvey.sex = sex
        contactSurvey.idNumber = idNumber
        contactSurvey.cellphone = cellphone
        contactSurvey.phone = phone
        contactSurvey.monthlyIncome = monthlyIncome
        contactSurvey.zipCode = zipCode
        contactSurvey.address = address
        contactSurvey.workUnitName = workUnitName
        contactSurvey.workUnitAddress = workUnitAddress
        contactSurvey.maritalStatus = maritalStatus

        if (identityTypeCode)
        {
            contactSurvey.identityType = ContactIdentityType.findById(identityTypeCode)
        }
        if (spouseIdentityTypeCode)
        {
            contactSurvey.spouseIdentityType = ContactIdentityType.findById(spouseIdentityTypeCode)
        }
        if (birthday)
        {
            contactSurvey.birthday = sdf.parse(birthday)
        }
        if (accountNatureCode)
        {
            contactSurvey.accountNature = AccountNatureDict.findByCode(accountNatureCode)
        }
        println "maritalStatus" + maritalStatus
        println "aaaaA   " + maritalStatus == "未婚"
        if (maritalStatus == "未婚" || maritalStatus == "离异" || maritalStatus == "丧偶")
        {
            println "fffffffff"
            contactSurvey.spouseFullName = ""
            contactSurvey.spouseCellphone = ""
            contactSurvey.spouseIdNumber = ""
        }
        else
        {
            println "hhhhhhhhhh"
            contactSurvey.spouseFullName = spouseFullName
            contactSurvey.spouseCellphone = spouseCellphone
            contactSurvey.spouseIdNumber = spouseIdNumber
        }
        def status
        if (contactSurvey.validate())
        {
            contactSurvey.save flush: true
            status = "success"
        }
        else
        {
            status = "fail"
            println contactSurvey.errors
        }
        println "contactSurvey.maritalStatus:  " + contactSurvey.maritalStatus
        render([status: status] as JSON)
    }

    //修改客户资信状况
    def editClientCreditStatus(ContactSurveyReport contactSurveyReport)
    {
        println "editClientCreditStatus params:  " + params
        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flash: true
        }
        else
        {
            println contactSurveyReport.errors
        }
        def contactSurveyList = contactSurveyReport.contacts
        println "contactSurveyList:  " + contactSurveyList
        respond contactSurveyReport, model: [contactSurveyList: contactSurveyList, contactSurveyReport: contactSurveyReport]

    }

    //修改客户所购房产情况
    def editClientCollateralPurchase(ContactSurveyReport contactSurveyReport)
    {

        respond contactSurveyReport
    }

    //修改客户贷款风险评估
    def editClientLoanRiskEvaluation(ContactSurveyReport contactSurveyReport)
    {

        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
        }
        respond contactSurveyReport
    }

    //修改客户贷款调查意见
    def editClientLoanOpinion(ContactSurveyReport contactSurveyReport)
    {

        if (contactSurveyReport.validate())
        {
            contactSurveyReport.save flush: true
        }
        respond contactSurveyReport
    }

    //借款人信息 接口查询
    def show1(Contact contact)
    {
        def result = developerApiService.getContactInfo("513001197308010223", "叶紫云")

        //单类处理返回List《map》
        //
        def gongkai = getByType(1, result)
        def laolai = getByType(2, result)
        def xiangao = getByType(3, result)
        def xianchu = getByType(4, result)
        def caipan = getByType(5, result)
        def shenpan = getByType(6, result)
        def zuifan = getByType(7, result)

        //贷款信息
        def mortgageList = MortgageContact.findAllByContact(contact)*.mortgage?.unique()
        respond true, model: [mortgageList: mortgageList, contactDetail: contact, gongkai: gongkai, laolai: laolai, xiangao: xiangao, xianchu: xianchu, caipan: caipan, shenpan: shenpan, zuifan: zuifan], view: 'show1'
    }

    def getByType(int x, def result)
    {
        List<Map<String, String>> list = new ArrayList<HashMap<String, String>>()
        String gongkai = "立案时间、被执行人姓名或名称、证件号码、执行案号、执行法院、执行标的、执行内容、执行状态、异议备注、终本日期、未履行金额、申请执行人"
        String laolai = "具体日期、被执行人姓名或名称、证件号码、执行案号、执行法院、执行内容、日期类别、执行状态、异议备注、省份、履行情况、具体情形、发布时间、执行依据文号、执行依据单位、未履行金额"
        String xiangao = "具体日期、被限制人姓名或名称、证件号码、执行案号、执行法院、执行内容、日期类别、执行状态、异议备注"
        String xianchu = "具体日期、被限制人姓名、证件号码、执行案号、执行法院、执行内容、日期类别、执行状态、异议备注"
        String caipan = "结案时间、当事人姓名或名称、证件号码、案号、诉讼地位、审理机关、文书类型、涉案事由、涉案金额、审理结果、审理程序、审理人员、异议备注、完整内容查看地址、原告当事人、被告当事人、其他当事人"
        String shenpan = "具体日期、当事人姓名或名称、证件号码、案号、诉讼地位、审理机关、公告类型、涉案事由、公告内容、日期类别、异议备注、所有当事人"
        String zuifan = "处理时间、当事人姓名或名称、证件号码、案号、侦查批捕审判机关、违法事由、处理结果、异议备注"
        def key = ""
        def arr
        switch (x)
        {
        case 1: key = "执行公开信息"; arr = gongkai; break;
        case 2: key = "失信老赖名单"; arr = laolai; break;
        case 3: key = "限制高消费名单"; arr = xiangao; break;
        case 4: key = "限制出入境名单"; arr = xianchu; break;
        case 5: key = "民商事裁判文书"; arr = caipan; break;
        case 6: key = "民商事审判流程"; arr = shenpan; break;
        case 7: key = "罪犯及嫌疑人名单"; arr = zuifan; break;
        default: break;
        }
        int i = 0
        result?.items?.each {
            if (it?.name == key)
            {
                def map = deal(it, arr.split("、"))
                if (map)
                {
                    list.add(map)
                }
            }
        }
        return list
    }

    def deal(def item, def arr)
    {
        def map = new HashMap()
        for (
            int i = 0;
                i < arr.length;
                i++)
        {
            item?.items.each {
                if (it?.name == arr[i])
                {
                    map.put(it?.name, it?.value)
                }
            }
        }
        return map
    }
}
